<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="80px">
      <el-form-item label="文件名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入文件名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['bid:bidfile:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['bid:bidfile:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['bid:bidfile:remove']"
        >删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="bidfileList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="文件名称" align="center" prop="name" />
      <el-table-column label="描述" align="center" prop="msg" />
      <el-table-column label="投标模板" align="center" prop="template" />
      <el-table-column label="创建者" align="center" prop="createByName" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['bid:bidfile:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['bid:bidfile:remove']"
          >删除</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="fileDownload(scope.row)"
            v-hasPermi="['bid:bidfile:export']"
          >下载</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改投标文件对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="70%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="文件名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入文件名称" />
        </el-form-item>
        <el-form-item label="描述" prop="msg">
          <el-input v-model="form.msg" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-row>
          <el-col :span="12">
            <el-form-item label="选择模型" prop="modelId">
              <el-select v-model="form.modelId" placeholder="请选择投标模型" @change="selModel">
                <el-option
                  v-for="dict in models"
                  :key="dict.id"
                  :label="dict.modelName"
                  :value="dict.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="下载模板" prop="template">
              <el-select v-model="form.template" placeholder="请选择投标模板">
                <el-option
                  v-for="dict in listConTemplates"
                  :key="dict.templateName"
                  :label="dict.templateName"
                  :value="dict.templateName"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-divider content-position="center">编辑内容</el-divider>


        <el-row v-for="(model, index) in crmBidModelContentList" :key="model.id">
          <el-col :span="24" :key="index">
            <el-form-item :label="model.modelColumnMsg+' \n\n ('+model.modelColumn+')'" prop="modelColumnContent">
              <editor v-model="model.modelColumnContent" :min-height="192"/>
            </el-form-item>
          </el-col>
        </el-row>


      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listBidfile, getBidfile, delBidfile, addBidfile, updateBidfile, exportBidfile } from "@/api/crm/bid/bidfile";
import { listAllModel, getModel } from "@/api/crm/bid/model";
import { fileDownload, listConTemplates } from "@/api/crm/templates/bid/templates";
import Editor from '@/components/Editor';

export default {
  name: "Bidfile",
  components: {
    Editor
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 子表选中数据
      checkedCrmBidModelContent: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 投标文件表格数据
      bidfileList: [],
      // 模型字段内容表格数据
      crmBidModelContentList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      //模型列表
      models:[],
      //模板列表
      listConTemplates: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [
          { required: true, message: "文件名称不能为空", trigger: "blur" }
        ],
        modelId: [
          { required: true, message: "模型不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
    listAllModel({isrelease:1}).then(response => {
      this.models = response.data;
    });
    listConTemplates().then(response => {
      this.listConTemplates = response;
    });
  },
  methods: {
    /** 选择模型 */
    selModel(modelId){
      getModel(modelId).then(response => {
        this.crmBidModelContentList = response.data.crmBidModelColumnList;
        this.crmBidModelContentList.forEach((item, index) => {
          item.modelColumnId = item.id;
        });
      });
    },
    /** 查询投标文件列表 */
    getList() {
      this.loading = true;
      listBidfile(this.queryParams).then(response => {
        this.bidfileList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        msg: null,
        template: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      };
      this.crmBidModelContentList = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加投标文件";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getBidfile(id).then(response => {
        this.form = response.data;
        this.crmBidModelContentList = response.data.crmBidModelContentList;
        console.log(response.data.crmBidModelContentList);
        this.open = true;
        this.title = "修改投标文件";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.crmBidModelContentList = this.crmBidModelContentList;
          if (this.form.id != null) {
            updateBidfile(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addBidfile(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除投标文件编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delBidfile(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
    },
	/** 模型字段内容序号 */
    rowCrmBidModelContentIndex({ row, rowIndex }) {
      row.index = rowIndex + 1;
    },
    /** 模型字段内容添加按钮操作 */
    handleAddCrmBidModelContent() {
      let obj = {};
      obj.modelColumnId = "";
      obj.modelColumnContent = "";
      obj.remark = "";
      this.crmBidModelContentList.push(obj);
    },
    /** 模型字段内容删除按钮操作 */
    handleDeleteCrmBidModelContent() {
      if (this.checkedCrmBidModelContent.length == 0) {
        this.$alert("请先选择要删除的模型字段内容数据", "提示", { confirmButtonText: "确定", });
      } else {
        this.crmBidModelContentList.splice(this.checkedCrmBidModelContent[0].index - 1, 1);
      }
    },
    /** 单选框选中数据 */
    handleCrmBidModelContentSelectionChange(selection) {
      if (selection.length > 1) {
        this.$refs.crmBidModelContent.clearSelection();
        this.$refs.crmBidModelContent.toggleRowSelection(selection.pop());
      } else {
        this.checkedCrmBidModelContent = selection;
      }
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有投标文件数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportBidfile(queryParams);
        }).then(response => {
          this.download(response.msg);
        })
    },
    /** 合同下载 */
    fileDownload(item){
      if(null == item.template){
        this.msgError("暂未指定合同模板");
      }else{
        fileDownload({id: item.id, template: item.template}).then(response => {
          let blob = new Blob([response], {
            type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
          }); // res就是接口返回的文件流了
          let url = window.URL || window.webkitURL;
          let fileURL = url.createObjectURL(blob);
          let a = document.createElement("a");
          a.href = fileURL;
          a.download = item.name + ".doc";
          a.target = "_self";
          a.click();
          url.revokeObjectURL(fileURL);
        });
      }
    }
  }
};
</script>
